package com.tarena.lbs.user.rpc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import com.tarena.lbs.user.dao.mapper.UserGroupMapper;
import com.tarena.lbs.user.dao.repository.UserTagsRepository;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.po.UserTagsPO;
import com.tarena.lbs.user.service.impl.AdminServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@DubboService
public  class UserApiImpl implements UserApi {

    @Autowired
    private AdminServiceImpl adminService;

    @Autowired
    private UserTagsRepository userTagsRepository;

    @Autowired
    private UserGroupMapper userGroupMapper;

    @Override
    public List<Integer> getUserGroupIds(Integer userId, Integer businessId) {
        log.debug("获取用户组ID列表，用户ID：{}，商家ID：{}", userId, businessId);
        
        try {
            // 1. 通过用户id查询用户所有的标签id（数据源：lbs_user_tags 表）
            List<UserTagsPO> userTagsList = userTagsRepository.findByUserId(userId);
            
            // 2. 判断用户标签id是否为空
            if (CollectionUtils.isEmpty(userTagsList)) {
                log.debug("用户{}没有绑定任何标签，返回空列表", userId);
                return Collections.emptyList();
            }
            
            // 3. 提取用户的标签ID列表
            List<Integer> userTagIds = userTagsList.stream()
                    .map(UserTagsPO::getTagId)
                    .collect(Collectors.toList());
            
            log.debug("用户{}的标签ID列表：{}", userId, userTagIds);
            
            // 4. 查询用户的标签id和商家的标签匹配的列表
            // 把用户的标签id列表和商家id作为条件查询匹配列表（数据源：lbs_user_group 表）
            List<Integer> matchedGroupIds = new ArrayList<>();
            
            for (Integer userTagId : userTagIds) {
                QueryWrapper<UserGroupPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("business_id", businessId);
                queryWrapper.like("tag_ids", userTagId.toString());
                
                List<UserGroupPO> matchedGroups = userGroupMapper.selectList(queryWrapper);
                
                for (UserGroupPO group : matchedGroups) {
                    if (!matchedGroupIds.contains(group.getId())) {
                        matchedGroupIds.add(group.getId());
                    }
                }
            }
            
            log.debug("用户{}匹配的用户分组ID列表：{}", userId, matchedGroupIds);
            return matchedGroupIds;
            
        } catch (Exception e) {
            log.error("获取用户组ID列表失败，用户ID：{}，商家ID：{}，错误：{}", userId, businessId, e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    @Override
    public AdminDto getAdminById(Integer adminId) {
        return adminService.detail(adminId);
    }
}
